package com.wn.EDI.util;

import com.wn.EDI.bean.DatEntityMo;
import com.wn.EDI.bean.DatEntityMt;
import com.wn.EDI.bean.DatEntityMth;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DatDumpModes
{
  public boolean datDumpMo(List<DatEntityMo> prdInfo, int ifTrial, String outPutFile)
  {
    File file = new File(outPutFile);

    if (file.exists())
      file.delete();
    try {
      file.createNewFile();
    } catch (IOException e1) {
      return false;
    }
    try
    {
      Writer wt = new OutputStreamWriter(new FileOutputStream(file));

      String ifTrialStr = new String();

      if (ifTrial == 1)
        ifTrialStr = "Y";
      else {
        ifTrialStr = "N";
      }
      SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

      String ibsCutCnt = ((DatEntityMo)prdInfo.get(0)).getIbxCutCnt();

      int pcs = 0;
      for (DatEntityMo demo : prdInfo)
      {
        pcs = pcs + Integer.parseInt(demo.getxAxisCnt()) * 
          Integer.parseInt(demo.getyAxisCnt());
      }
      String pcsS = String.valueOf(pcs);

      for (Iterator localIterator2 = prdInfo.iterator(); localIterator2
        .hasNext(); 
        wt.write(";\r\n")) {
        DatEntityMo demo = (DatEntityMo)localIterator2.next();

        wt.write(demo.getPanelId());
        wt.write(",");

        int i = 0;

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 199);
        wt.write(",");

        wt.write(demo.getDpartNo());
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 19);
        wt.write(",");

        wt.write(demo.getInboxId());
        wt.write(",");

        String cfgTime = demo.getInboxIdCfgTime();
        if (cfgTime != null)
          wt.write(fmt2.format(fmt.parse(demo.getInboxIdCfgTime())));
        else
          forWriteSpace(wt, 19);
        wt.write(",");

        wt.write(demo.getOutboxId());
        wt.write(",");

        cfgTime = demo.getOutboxIdCfgTime();
        if (cfgTime != null)
          wt.write(fmt2.format(fmt.parse(demo.getOutboxIdCfgTime())));
        else
          forWriteSpace(wt, 19);
        wt.write(",");

        wt.write("U");
        wt.write(",");

        forWriteSpace(wt, 4);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 10);
        wt.write(",");

        forWriteSpace(wt, 12);
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 10);
        wt.write(",");

        forWriteSpace(wt, 10);
        wt.write(",");

        forWriteSpace(wt, 11);
        wt.write(",");

        forWriteSpace(wt, 11);
        wt.write(",");

        forWriteSpace(wt, 11);
        wt.write(",");

        forWriteSpace(wt, 11);
        wt.write(",");

        forWriteSpace(wt, 11);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(ibsCutCnt);
        wt.write(" ");

        forWriteSpace(wt, 5);
        wt.write(",");

        for (i = pcsS.length(); i < 5; i++)
          wt.write(" ");
        wt.write(pcsS);
        wt.write(",");

        forWriteSpace(wt, 999);
        wt.write(",");

        forWriteSpace(wt, 10);
        wt.write(",");

        forWriteSpace(wt, 4);
        wt.write(",");

        wt.write(ifTrialStr);
        wt.write(",");

        forWriteSpace(wt, 10);
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 2);
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 7);
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 3);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 20);
        wt.write(",");

        forWriteSpace(wt, 64);
        wt.write(",");

        forWriteSpace(wt, 2);
        wt.write(",");

        forWriteSpace(wt, 2);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 10);
        wt.write(",");

        forWriteSpace(wt, 10);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 20);
        wt.write(",");

        forWriteSpace(wt, 20);
        wt.write(",");

        forWriteSpace(wt, 64);
        wt.write(",");

        forWriteSpace(wt, 14);
        wt.write(",");

        forWriteSpace(wt, 4);
        wt.write(",");

        forWriteSpace(wt, 20);
        wt.write(",");

        forWriteSpace(wt, 64);
        wt.write(",");

        forWriteSpace(wt, 14);
        wt.write(",");

        forWriteSpace(wt, 20);
        wt.write(",");

        forWriteSpace(wt, 7);
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 2);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 2);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 2);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 4);
        wt.write(",");

        forWriteSpace(wt, 198);
        wt.write(",");

        forWriteSpace(wt, 4);
        wt.write(",");

        forWriteSpace(wt, 4);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 6);
        wt.write(",");

        forWriteSpace(wt, 5);
        wt.write(",");

        forWriteSpace(wt, 8);
        wt.write(",");

        forWriteSpace(wt, 2);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        forWriteSpace(wt, 99);
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        wt.write(" ");
        wt.write(",");

        forWriteSpace(wt, 10);
      }

      wt.flush();
      wt.close();
    } catch (FileNotFoundException e) {
      return false;
    } catch (IOException e) {
      return false;
    } catch (ParseException e) {
      return false;
    }
    return true;
  }

  public boolean datDumpMt(List<DatEntityMt> datMtList, String outPutFile) {
    File file = new File(outPutFile);

    if (file.exists())
      file.delete();
    try {
      file.createNewFile();
    } catch (IOException e1) {
      return false;
    }
    try
    {
    	Writer wt = new OutputStreamWriter(new FileOutputStream(file));
    	String inBoxId = ((DatEntityMt)datMtList.get(0)).getInboxId();
    	String pnlCnt = ((DatEntityMt)datMtList.get(0)).getPnlCnt();
    	String outBoxId = ((DatEntityMt)datMtList.get(0)).getOutboxId();
    	String cate = ((DatEntityMt)datMtList.get(0)).getCate();
    	String mtrl = ((DatEntityMt)datMtList.get(0)).getMtrl();
    	String mdl = "";
    	if (cate.endsWith("A")) {
    	    mdl = ((DatEntityMt)datMtList.get(0)).getMdl();
    	} else if (cate.endsWith("B")) {
    	    mdl = ((DatEntityMt)datMtList.get(0)).getFm();
    	} else if (cate.endsWith("C")) {
    	    mdl = ((DatEntityMt)datMtList.get(0)).getCut();
    	}

    	if (inBoxId == null || "".equals(inBoxId)) {
    	    inBoxId = "*";
    	}

      int i ;
    	for(i = inBoxId.length(); i < 7; ++i) {
    	    inBoxId = inBoxId + " ";
    	}

    	for(i = mdl.length(); i < 20; ++i) {
    	    mdl = mdl + " ";
    	}

    	wt.write("001 " + inBoxId + ",");
    	String space = new String();

    	for(i = pnlCnt.length(); i < 2; ++i) {
    	    space = space + "0";
    	}

    	wt.write(space + pnlCnt + ",");
    	wt.write(outBoxId + "," + mdl + "," + mtrl + ";\r\n");
    	space = "";

    	for(Iterator var13 = datMtList.iterator(); var13.hasNext(); space = "") {
    	    DatEntityMt datMt = (DatEntityMt)var13.next();

    	    for( i = datMt.getPanelId().length(); i < 10; ++i) {
    	        space = space + " ";
    	    }

    	    wt.write("002 " + datMt.getPanelId() + space + ";\r\n");
    	}

      wt.write("999 END\n");

      wt.flush();
      wt.close();
    } catch (FileNotFoundException e) {
      return false;
    } catch (IOException e) {
      return false;
    }
    return true;
  }

  public boolean datDumpMth(String box_id, String cusId, List<DatEntityMth> dEMth, String outPutFile, int fullQty)
  {
    File file = new File(outPutFile);

    if (file.exists())
      file.delete();
    try {
      file.createNewFile();
    } catch (IOException e1) {
      return false;
    }

    DatEntityMth dat = (DatEntityMth)dEMth.get(0);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder builder = factory.newDocumentBuilder();

      Document document = builder.newDocument();

      Element root = document.createElement("BODY");
      document.appendChild(root);

      Element tpon = document.createElement("TPONCELLONLY");

      Element direction = document.createElement("DIRECTION");
      if ("071".equals(cusId)){
        direction.appendChild(document.createTextNode("WGTWH"));
      } else if ("168".equals(cusId) || "169".equals(cusId)) {
        direction.appendChild(document.createTextNode(""));
      }else {
        direction.appendChild(document.createTextNode("WGTCD"));
      }
      tpon.appendChild(direction);

      Element makerid = document.createElement("MAKERID");
      makerid.appendChild(document.createTextNode("WG"));
      tpon.appendChild(makerid);

      Element fabid = document.createElement("FABID");
      if ("071".equals(cusId)){
        fabid.appendChild(document.createTextNode("A1"));
      } else if ("168".equals(cusId) || "169".equals(cusId)) {
        fabid.appendChild(document.createTextNode("2"));
      } else {
        fabid.appendChild(document.createTextNode("E1"));
      }

      tpon.appendChild(fabid);
      //088,071,028 需要realboxid
      if ("088".equals(cusId) || "071".equals(cusId) || "028".equals(cusId)){
        Element realboxid = document.createElement("BOXNAME");
        realboxid.appendChild(document.createTextNode(StringUtils.isBlank(dat.getRealboxid()) ? "" : dat.getRealboxid()));

        tpon.appendChild(realboxid);
      }

      Element shipdate = document.createElement("SHIPDATE");
      shipdate.appendChild(document.createTextNode(dat.getShipDate()));
      tpon.appendChild(shipdate);

      Element ppboxId = document.createElement("PPBOXID");
      if ("168".equals(cusId) || "169".equals(cusId)){
        ppboxId.appendChild(document.createTextNode(box_id));
      }else {
        if (dat.getPpboxId() == null)
          ppboxId.appendChild(document.createTextNode("*"));
        else {
          ppboxId.appendChild(document.createTextNode(dat.getPpboxId()));
        }
      }

      tpon.appendChild(ppboxId);

      Element thickness = document.createElement("THICKNESS");
      if (("0.4".equals(dat.getT_thickness())) && ("0.4".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("A"));
      else if (("0.5".equals(dat.getT_thickness())) && ("0.5".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("B"));
      else if (("0.6".equals(dat.getT_thickness())) && ("0.6".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("C"));
      else if (("0.63".equals(dat.getT_thickness())) && ("0.63".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("D"));
      else if (("0.7".equals(dat.getT_thickness())) && ("0.7".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("E"));
      else if (("1.1".equals(dat.getT_thickness())) && ("1.1".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("F"));
      else if (("0.2".equals(dat.getT_thickness())) && ("0.2".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("G"));
      else if (("0.3".equals(dat.getT_thickness())) && ("0.3".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("H"));
      else if (("0.25".equals(dat.getT_thickness())) && ("0.35".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("J"));
      else if (("0.225".equals(dat.getT_thickness())) && ("0.225".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("K"));
      else if (("0.63".equals(dat.getT_thickness())) && ("0.7".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("L"));
      else if (("0.215".equals(dat.getT_thickness())) && ("0.215".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("M"));
      else if (("0.265".equals(dat.getT_thickness())) && ("0.265".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("N"));
      else if (("0.1".equals(dat.getT_thickness())) && ("0.1".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("P"));
      else if (("0.15".equals(dat.getT_thickness())) && ("0.15".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("Q"));
      else if (("0.2".equals(dat.getT_thickness())) && ("0.1".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("S"));
      else if (("0.18".equals(dat.getT_thickness())) && ("0.18".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("T"));
      else if (("0.5".equals(dat.getT_thickness())) && ("0.4".equals(dat.getC_thickness())))
        thickness.appendChild(document.createTextNode("R"));
      else if (("0.2".equals(dat.getT_thickness())) && ("0.4".equals(dat.getC_thickness()))) {
        thickness.appendChild(document.createTextNode("U"));
      }
      if ("168".equals(cusId) || "169".equals(cusId)) {
        thickness.appendChild(document.createTextNode(dat.getThickness()));
      }
      tpon.appendChild(thickness);
      root.appendChild(tpon);

      Map map = new LinkedHashMap();
      for (DatEntityMth dem : dEMth) {
        if (map.containsKey(dem.getLotId()))
          map.put(dem.getLotId(), Integer.valueOf(((Integer)map.get(dem.getLotId())).intValue() + 1));
        else {
          map.put(dem.getLotId(), Integer.valueOf(1));
        }
      }
      Iterator iter = map.entrySet().iterator();
      Element lotInfo;
      while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry)iter.next();
        lotInfo = document.createElement("LOTINFO");

        Element lotId = document.createElement("LOTID");
        lotId.appendChild(document.createTextNode(entry.getKey().toString()));
        lotInfo.appendChild(lotId);

        Element product = document.createElement("PRODUCT");
        if (!isSpaceCheck(dat.getCutproduct()))
          product.appendChild(document.createTextNode(dat.getCutproduct()));
        else if (!isSpaceCheck(dat.getDmproduct()))
          product.appendChild(document.createTextNode(dat.getDmproduct()));
        else {
          product.appendChild(document.createTextNode(dat.getJbproduct()));
        }
        lotInfo.appendChild(product);

        Element qty = document.createElement("QTY");
        qty.appendChild(document.createTextNode(String.valueOf(entry.getValue())));
        lotInfo.appendChild(qty);

        Element slot = document.createElement("SLOT");

        String slotStr = "";
        List cpDEMth = new ArrayList();
        cpDEMth.addAll(dEMth);

        fullQty = Integer.valueOf(((DatEntityMth)cpDEMth.get(cpDEMth.size() - 1)).getSlotNo()).intValue() > fullQty ? Integer.valueOf(((DatEntityMth)cpDEMth.get(cpDEMth.size() - 1)).getSlotNo()).intValue() : fullQty;

        for (int i = 1; i <= fullQty; i++) {
          boolean flag = false;

          for (int j = 0; j < cpDEMth.size(); j++)
          {
            if (String.valueOf(i).equals(((DatEntityMth)cpDEMth.get(j)).getSlotNo())) {
              flag = true;
              cpDEMth.remove(j);
              break;
            }
          }

          if (flag)
            slotStr = slotStr + "O";
          else {
            slotStr = slotStr + "X";
          }
        }

        slot.appendChild(document.createTextNode(slotStr));
        lotInfo.appendChild(slot);
        
        if ("168".equals(cusId) && dEMth != null && dEMth.size() > 0) {
          Element grade = document.createElement("GRADE");
          grade.appendChild(document.createTextNode(dEMth.get(0).getReasonCode()));
          lotInfo.appendChild(grade);
        }
        if ("169".equals(cusId) && dEMth != null && dEMth.size() > 0) {
            Element grade = document.createElement("GRADE");
            grade.appendChild(document.createTextNode(dEMth.get(0).getReasonCode()));
            lotInfo.appendChild(grade);
          }

        root.appendChild(lotInfo);
      }

      for (DatEntityMth dem : dEMth) {
        Element glsInfo = document.createElement("GLSINFO");

        Element slotNo = document.createElement("SLOTNO");
        slotNo.appendChild(document.createTextNode(dem.getSlotNo()));
        glsInfo.appendChild(slotNo);

        Element glotId = document.createElement("LOTID");
        glotId.appendChild(document.createTextNode(dem.getLotId()));
        glsInfo.appendChild(glotId);

        Element glsId = document.createElement("GLSID");
        if ("168".equals(cusId) || "169".equals(cusId)) {
          if (dem.getFabSn().length() > 9)
            glsId.appendChild(document.createTextNode(dem.getFabSn().substring(0, 9)));
          else {
            glsId.appendChild(document.createTextNode(dem.getFabSn()));
          }
        }else {
          if (dem.getGlsId().length() > 10)
            glsId.appendChild(document.createTextNode(dem.getGlsId().substring(0, 10)));
          else {
            glsId.appendChild(document.createTextNode(dem.getGlsId()));
          }
        }
        glsInfo.appendChild(glsId);

        Element resonCode = document.createElement("REASONCODE");
        if ("OK".equals(dem.getReasonCode()))
          resonCode.appendChild(document.createTextNode("P"));
        else {
          resonCode.appendChild(document.createTextNode(dem.getReasonCode()));
        }
        if (!("168".equals(cusId) || "169".equals(cusId))) {
          glsInfo.appendChild(resonCode);
        }

        root.appendChild(glsInfo);
      }

      TransformerFactory tf = TransformerFactory.newInstance();

      Transformer transformer = tf.newTransformer();
      DOMSource source = new DOMSource(document);
      transformer.setOutputProperty("encoding", "utf-8");
      transformer.setOutputProperty("indent", "yes");

      Writer wt = new OutputStreamWriter(new FileOutputStream(file));
      StreamResult result = new StreamResult(wt);

      transformer.transform(source, result);
      wt.flush();
      wt.close();

      return true;
    } catch (TransformerConfigurationException e) {
      System.out.println(e.getMessage());
      return false;
    } catch (ParserConfigurationException e) {
      System.out.println(e.getMessage());
      return false;
    } catch (DOMException e) {
      System.out.println(e.getMessage());
      return false;
    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
      return false;
    } catch (TransformerException e) {
      System.out.println(e.getMessage());
      return false;
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
    return false;
  }

  private void forWriteSpace(Writer wt, int length) throws IOException {
    for (int i = 0; i < length; i++)
      wt.write(" ");
  }

  private boolean isSpaceCheck(String str) {
    if ((str == null) || (str.length() <= 0) || ("".equals(str))) {
      return true;
    }
    return false;
  }
}